<template>
  <div class="container">
    <div class="app-container">
      <!-- 实现添加页面权限 -- pid固定为0 -->
      <el-button type="primary" size="mini" @click="add(0)">添加权限</el-button>
      <!-- 表格渲染树形结构需要满足2个条件：
      1/ table组件需要添加row-key属性
      2/ 数据中子级要嵌套在children属性中
       -->
      <el-table :data="permList" row-key="id">
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="code" label="标识" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作">
          <template v-slot="{row}">
            <!-- 实现添加按钮权限 -->
            <el-button v-if="row.type===1" type="text" @click="add(row.id)">添加</el-button>
            <el-button type="text" @click="edit(row.id)">编辑</el-button>
            <el-button type="text" @click="del(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 新增权限 -->
      <AddPerm
        ref="addPerm"
        :pid="pid"
        :show-dialog.sync="isShow"
        @updateEvent="getPermList"
      />
    </div>
  </div>
</template>
<script>
/**
 * 需求1：列表渲染
 * 1、封装接口函数
 * 2、在created中调用接口函数并保存数据
 * 3、根据保存的数据进行渲染
 *
 * */
import { permissionList, deletePerm } from '@/api/permission'
import { transListToTreeData } from '@/utils'
import AddPerm from './components/add-perm.vue'
export default {
  name: 'Permission',
  components: { AddPerm },
  data() {
    return {
      permList: [],
      isShow: false,
      pid: '',
      type: ''
    }
  },
  created() {
    this.getPermList()
  },
  methods: {
    // 获取权限列表
    async getPermList() {
      const res = await permissionList()
      // 列表转树形结构
      this.permList = transListToTreeData(res, 0)
    },
    // 新增权限
    add(id) {
      this.isShow = true
      this.pid = id
    },
    // 编辑权限
    edit(id) {
      this.add(id)
      this.$refs.addPerm.getPermDetails(id)
    },
    // 删除
    del(id) {
      this.$confirm('确定删除该数据吗？', '提示').then(async() => {
        await deletePerm(id)
        this.$message.success('删除成功！')
        this.getPermList()
      }).catch((err) => {
        console.log(err)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container{
  padding: 10px;
  .el-table {
    margin-top: 20px;
  }
}
</style>
